<template>
  <view class="container">
    <u-navbar
      :title="$t('projectList.pageTitle')"
      leftIconSize="0"
      :titleStyle="{
        fontSize: '36rpx',
        fontWeight: 600
      }"
      :autoBack="false"
    >
      <template #left>
        <text @click="handleExit" class="navbar__content__left__text">{{
          $t('common.quitBtn')
        }}</text>
      </template>
    </u-navbar>

    <view class="tabs-bar">
      <u-tabs
        :list="tabs_list"
        lineWidth="20"
        :lineHeight="0"
        :activeStyle="{
          color: '#4187FF',
          fontWeight: 'bold',
          fontSize: '36rpx'
        }"
        :inactiveStyle="{
          color: '#999999',
          fontSize: '30rpx'
        }"
        itemStyle="padding-left: 15rpx; padding-right: 15rpx; "
        @click="onClickTab"
      ></u-tabs>
    </view>
    <view class="project-list">
      <ProjectList :project_list="currentProjectList"></ProjectList>
    </view>

    <view v-if="!isShowPopup">
      <drag-button :isDock="true" :existTabBar="true" @btnClick="handleDragBtnClick" />
    </view>
    <u-popup
      :show="isShowPopup"
      mode="center"
      closeOnClickOverlay
      :round="10"
      :customStyle="{
        width: '90% !important'
      }"
      :safeAreaInsetBottom="false"
      @close="isShowPopup = false"
    >
      <view class="popup-container">
        <view class="popup-title">{{ $t('projectList.emailContent') }}</view>
        <u-form labelPosition="left" :model="info" :rules="rules" ref="FormRef" labelWidth="120">
          <u-form-item :label="$t('projectList.recipientname')" prop="recipient_name" ref="item0">
            <u--input
              v-model="info.recipient_name"
              border="bottom"
              :placeholder="$t('projectList.recipientnamePlaceholder')"
            ></u--input>
          </u-form-item>
          <u-form-item :label="$t('projectList.email')" prop="email" ref="item1">
            <u--input
              v-model="info.email"
              border="bottom"
              :placeholder="$t('projectList.emailPlaceholder')"
            ></u--input>
          </u-form-item>
          <u-form-item :label="$t('projectList.carbonEmail')" prop="cc_email" ref="item2">
            <u--input
              v-model="info.cc_email"
              border="bottom"
              :placeholder="$t('projectList.ccEmailPlaceholder')"
            ></u--input>
          </u-form-item>
        </u-form>

        <div class="checkbox-wrap">
          <u-checkbox-group v-model="isShow">
            <u-checkbox label="不再提示" :name="0" />
          </u-checkbox-group>
        </div>

        <div class="btn-wrap">
          <div class="confirm-btn-wrap">
            <u-button @click="handleSubmit" class="confirm-btn">{{
              $t('projectList.popupConfirm')
            }}</u-button>
          </div>
          <div style="margin-left: 5px">
            <u-button @click="isShowPopup = false">{{ $t('projectList.popupCancel') }}</u-button>
          </div>
        </div>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { LOGINPATCH } from '@/constants/router/subPackages'
import storage from '@/utils/storage'
import { getProjectList } from '@/api/me/index'
import { USER_INFO } from '@/store/mutation-types'
import ProjectList from './components/ProjectList/ProjectList.vue'
import { sendEmail } from '@/api/productList'
import { getCustomerDetail } from '@/api/user'

export default {
  data() {
    return {
      isShow: [],
      current_status: 1,
      tabs_list: [
        { name: this.$t('projectList.onGoing'), status: 1 },
        { name: this.$t('projectList.completed'), status: 2 }
      ],
      user_info: undefined,
      // 缓存数据结构
      project_data: {
        1: {
          // ongoing projects
          list: [],
          page: 1,
          hasMore: true
        },
        2: {
          // completed projects
          list: [],
          page: 1,
          hasMore: true
        }
      },
      loading: false,
      isShowPopup: false,
      info: {
        email: '',
        cc_email: '',
        recipient_name: ''
      },
      rules: {
        email: {
          type: 'email',
          required: false,
          message: this.$t('projectList.emailValidErrorMsg'),
          trigger: ['blur', 'change']
        },
        cc_email: {
          type: 'email',
          required: false,
          message: this.$t('projectList.emailValidErrorMsg'),
          trigger: ['blur', 'change']
        },
        recipient_name: {
          type: 'string',
          required: false,
          message: this.$t('projectList.recipientnamePlaceholder'),
          trigger: ['blur', 'change']
        }
      }
    }
  },
  computed: {
    // 获取当前状态对应的项目列表
    currentProjectList() {
      return this.project_data[this.current_status].list
    }
  },
  methods: {
    handleExit() {
      uni.showModal({
        title: this.$t('login.exitTitle'),
        content: this.$t('login.exitContent'),
        cancelText: this.$t('login.exitCancel'),
        confirmText: this.$t('login.exitConfirm'),
        success: (res) => {
          if (res.confirm) {
            storage.clear()
            uni.reLaunch({ url: LOGINPATCH })
          }
        }
      })
    },
    // 切换标签时，根据缓存判断是否需要请求
    onClickTab(item) {
      this.current_status = item.status
      const currentData = this.project_data[this.current_status]

      // 若已缓存的数据不足一页（即没有加载完全），才进行加载
      if (currentData.page === 1 && currentData.list.length === 0) {
        this.loadProjectList()
      }
    },
    // 通用的加载项目列表方法
    async loadProjectList(config = {}) {
      const currentData = this.project_data[this.current_status]

      // 如果已经在加载或没有更多数据则返回
      if (this.loading || !currentData.hasMore) return

      this.loading = true
      try {
        const {
          result: { items: list }
        } = await getProjectList(
          {
            page: currentData.page,
            pageSize: 10,
            client_id: this.user_info.userId,
            status: this.current_status
          },
          config
        )

        // 将新的数据追加到缓存的列表中
        currentData.list = [...currentData.list, ...list]

        // 判断是否还有更多数据
        if (list.length < 10) {
          currentData.hasMore = false
        } else {
          currentData.page += 1
        }
      } catch (error) {
        console.error('加载项目列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    handleDragBtnClick() {
      this.isShowPopup = true
    },
    async handleSubmit() {
      try {
        await this.$refs.FormRef.validate()
        const { result: msg } = await sendEmail({
          email: this.info.email || '',
          cc_email: this.info.cc_email || '',
          recipient_name: this.info.recipient_name || '',
          id: Number(this.user_info.userId),
          is_show: this.isShow.includes(0) ? 0 : 1
        })

        this.isShowPopup = false
        uni.$u.toast('submit ' + msg.msg)
      } catch (err) {
        uni.$u.toast(this.$t('common.submitFail'))
      }
    },
    async handleGetCustomerDetail() {
      try {
        // if (!this.user_info || !this.user_info.userId) return
        const { result } = await getCustomerDetail(this.user_info.userId, { loading: false })
        this.info.email = result.email
        this.info.cc_email = result.cc_email
        if (result.is_show === 1) {
          this.isShowPopup = true
        } else if (result.is_show === 0) {
          this.isShow = [result.is_show]
        }
      } catch (err) {
        uni.$u.toast(this.$t('common.initFail'))
      }
    }
  },
  async onLoad() {
    if (!storage.get(USER_INFO)) return
    this.user_info = storage.get(USER_INFO)
    if (this.user_info && this.user_info.email) this.info.email = this.user_info.email
    if (this.user_info && this.user_info.cc_email) this.info.cc_email = this.user_info.cc_email
    uni.showLoading({
      title: this.$t('common.loading'),
      mask: true
    })
    await this.loadProjectList({ loading: false })
    await this.handleGetCustomerDetail()
    uni.hideLoading()
  },
  // mounted() {
  // this.handleGetCustomerDetail()
  // },
  onReachBottom() {
    this.loadProjectList()
  },
  components: {
    ProjectList
  },
  watch: {
    info: {
      handler(val) {
        this.rules.recipient_name.required = !!val.email
        this.rules.email.required = !!val.recipient_name
      },
      deep: true
    }
  }
}
</script>

<style lang="scss" scoped>
@import './css/index.scss';
</style>
